let fs = require('fs')
let os = require('os')
let path = require('path')
let exec = require('child_process').exec
let promisify = require('util').promisify
let mime = require('mime-types')

let readDir = promisify(fs.readdir)
let readFile = promisify(fs.readFile)

async function readFiles(directory) {
  let files = await readDir(directory)
  // 过滤文件名中包含`.`的
  return files
    .filter(file => !file.startsWith('.'))
    .map(file => ({ name: file }))
}

async function renderFiles({
  fileMapList = [],
  breadCrumbList = [],
  pathname
}) {
  if (
    (!Array.isArray(fileMapList) || fileMapList.length === 0) &&
    (!Array.isArray(breadCrumbList) || breadCrumbList.length === 0)
  ) {
    return render('')
  }

  let list = fileMapList.map(({ name, clzName, href }) => {
    return `
      <li>
        <a
          class="${clzName}"
          href="${href}"
        >
          <span
            class="name"
          >
            ${name}
          </span>
        </a>
      </li>
    `
  })

  let navHtml = ''
  if (breadCrumbList.length) {
    navHtml = `
      <h1>
        ${breadCrumbList
          .map(item => {
            let { href, value } = item
            return `<a href="${href}">${value}</a> / `
          })
          .join('')}
      </h1>
    `
  }

  let html = `
    <div>
      ${navHtml}
      <ul id="files">
        ${list.join('')}
      </ul>
    </div>
  `

  return render(html, { title: pathname })
}

function render(content, { title = '/' } = {}) {
  return `
  <html>
    <head>
      <meta charset="utf-8" />
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
      />
      <title>directory ${title}</title>
      <link rel="stylesheet" href="/src/assets/style.css" />
      <link rel="stylesheet" href="/src/assets/icon.css" />
    </head>
    <body class="directory">
      ${content}
    </body>
  </html>
  `
}

/**
 * 打开默认浏览器
 */
function openBrowser(url) {
  let command = 'open'
  let osType = os.type()
  if (osType === 'Linux') {
    command = 'x-www-browser'
  } else if (osType === 'Windows_NT') {
    command = 'start'
  }
  exec(`${command} ${url}`)
}

module.exports = {
  readFile,
  readFiles,
  promisify,
  renderFiles,
  openBrowser
}
